package com.flow.demo.module.gd.service.good;

import com.flow.demo.module.gd.controller.app.good.vo.GoodPageReqVO;
import com.flow.demo.module.gd.controller.app.good.vo.GoodSaveReqVO;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import com.flow.demo.module.gd.dal.dataobject.good.GoodDO;
import com.flow.demo.framework.common.pojo.PageResult;
import com.flow.demo.framework.common.util.object.BeanUtils;

import com.flow.demo.module.gd.dal.mysql.good.GoodMapper;

import javax.annotation.Resource;

import static com.flow.demo.framework.common.exception.enums.GlobalErrorCodeConstants.GOOD_NOT_EXISTS;
import static com.flow.demo.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 奖品 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class GoodServiceImpl implements GoodService {

    @Resource
    private GoodMapper goodMapper;

    @Override
    public Integer createGood(GoodSaveReqVO createReqVO) {
        // 插入
        GoodDO good = BeanUtils.toBean(createReqVO, GoodDO.class);
        goodMapper.insert(good);
        // 返回
        return good.getPrizeId();
    }

    @Override
    public void updateGood(GoodSaveReqVO updateReqVO) {
        // 校验存在
        validateGoodExists(updateReqVO.getPrizeId());
        // 更新
        GoodDO updateObj = BeanUtils.toBean(updateReqVO, GoodDO.class);
        goodMapper.updateById(updateObj);
    }

    @Override
    public void deleteGood(Integer id) {
        // 校验存在
        validateGoodExists(id);
        // 删除
        goodMapper.deleteById(id);
    }

    private void validateGoodExists(Integer id) {
        if (goodMapper.selectById(id) == null) {
            throw exception(GOOD_NOT_EXISTS);
        }
    }

    @Override
    public GoodDO getGood(Integer id) {
        return goodMapper.selectById(id);
    }

    @Override
    public PageResult<GoodDO> getGoodPage(GoodPageReqVO pageReqVO) {
        return goodMapper.selectPage(pageReqVO);
    }

}
